import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:crypto/crypto.dart';
import '../../public.dart';

/// request拦截器
class RequestInterceptors extends InterceptorsWrapper {
  @override
  onRequest(RequestOptions options) async {
    /// 超时
    options.connectTimeout = 5000;
    if (options.headers['access-token'] == null) {
      if (ACGN.accessToken != null) {
        options.headers['access-token'] = ACGN.accessToken;
      }
    }
    setProductLine(options);

    /// 请求效验串
    options.headers['m-request-id'] = generateRequesetId(options);
    return options;
  }

  void setProductLine(RequestOptions options) {
    String platformname = AppConfig.platformname;
    String productname = AppConfig.PRODUCTNAME;
    if (options.method == 'POST') {
      options.data['productname'] = productname;
      options.data['platformname'] = platformname;
    } else {
      options.queryParameters['productname'] = productname;
      options.queryParameters['platformname'] = platformname;
    }
  }

  /// 生成m-request-id
  String generateRequesetId(RequestOptions options) {
    RegExp mobile = new RegExp(r'https?://(?:[^/]+)(/.*)');
    var match = mobile.firstMatch(options.uri.toString());
    String strEncode = match.group(1).replaceAll('?', '');
    LogUtil.v('url===>${options.uri.toString()}');
    if (options.method == 'POST') {
      Map<String, dynamic> dataParameters = options.data;
      List<String> sortKeys = dataParameters.keys.toList()..sort();
      List<String> arrEncode = [];
      sortKeys.forEach((item) {
        arrEncode.add('$item=${dataParameters[item]}');
      });
      strEncode = strEncode + arrEncode.join('&');
    }
    return generateMD5RequesetId(strEncode, AppConfig.QUEST_KEY);
  }

  String generateMD5RequesetId(String strEncode, String salt) {
    String strEncodeAndSalt = '$strEncode$salt';
    LogUtil.v('strEncodeAndSalt===>$strEncodeAndSalt');
    String requestId = md5.convert(utf8.encode(strEncodeAndSalt)).toString();
    LogUtil.v('m-request-id===>$requestId');
    return requestId;
  }
}
